package WebTools::Weather;
use strict;
use warnings;
use utf8;

use base qw/WebCore/;
use Encode;
use Tools::IPCheck;
use Storable;
use File::Spec;
use Cwd;
use DateTime;
use Data::Dumper;

use WebModule::Wcity;
use WebModule::Wcity::Manager;
use WebModule::Wprovince;
use WebModule::Wprovince::Manager;


sub home:Default {#{{{
    my $this = shift;

    #首先需要根据IP得到所在的市
    my $ip = &get_ip();
    my $city_name = &check_city($ip, $this->config('ip_db'));

    if ( $city_name eq '本机地址' ) {
        $city_name = '北京市';
    }

    #判断一下最后一个字符，拿掉随后一个字
    $city_name = substr $city_name, 0, length($city_name)-1;

    
    #得到城市的ID
    my $city_id = 1;
    my $city_object = WebModule::Wcity->new('city'=>encode('utf-8', $city_name));
    if ( $city_object->load(speculative=>1) ) {
        $city_id = $city_object->id;
    }
    
    #得到cityid的天气数据文件
    my $local = DateTime::TimeZone->new( name=>'Asia/Shanghai');
    my $now = DateTime->now(time_zone=>$local);
    my $dir_name = $now->year.$now->month.$now->day;
    my $file_ext = $now->year.$now->month.$now->day;

    my $data_file = File::Spec->catfile($this->config('weather_db'), $dir_name, $file_ext.'_'.$city_id.'.data');

   
    my $weather_ref = eval {
        retrieve($data_file);
    };


    #得到所有的直辖市和省
    my $provinces = WebModule::Wprovince::Manager->get_wprovince;



    $this->set_tt_var('weathers', $weather_ref);
    $this->set_tt_var('city_name', $city_name);
    $this->set_tt_var('provinces', $provinces);
    $this->set_tt_var('customer_title', '天气预报 - 5anet.com');
    return $this->process_template('weather.tt2');
}#}}}


#列表显示城市
sub listcity:Regex('listcity/(\d+)') {#{{{
    my $this = shift;
    my ($province_id) = $this->action_args;

    my $cities = WebModule::Wcity::Manager->get_wcity(
        query=>[
        province=>$province_id,
        ],
        sort_by=>'id asc',
    );

    #显示模板
    $this->set_tt_var('cities', $cities);
    $this->set_tt_var('customer_title', '城市预报 天气预报 - 5anet.com');
    return $this->process_template('weatherlistcity.tt2');
}#}}}


#显示城市天气
sub city:Regex('city/(\d+)') {
    my $this = shift;
    my ($city_id) = $this->action_args;

    #根据城市的ID得到现有的城市的天气数据
    my $local = DateTime::TimeZone->new( name=>'Asia/Shanghai');
    my $now = DateTime->now(time_zone=>$local);
    my $dir_name = $now->year.$now->month.$now->day;
    my $file_ext = $now->year.$now->month.$now->day;

    my $data_file = File::Spec->catfile($this->config('weather_db'), $dir_name, $file_ext.'_'.$city_id.'.data');

   
    my $weather_ref = eval {
        retrieve($data_file);
    };

    my $city = WebModule::Wcity->new(id=>$city_id);
    $city->load(speculative=>1);



    #显示模板
    $this->set_tt_var('weathers', $weather_ref);
    $this->set_tt_var('city', $city);
    $this->set_tt_var('customer_title', '城市预报 '.$city->city.' - 5anet.com');
    return $this->process_template('weathercity.tt2');


}



1;
